import { cloneDeep } from "lodash";
import { analUserAgent } from "./browser";
import JSEncrypt from "jsencrypt";
import { clerStorage } from "./storage/storage";
import router from "@/router";
export const logout = ()=>{
    clerStorage()
    router?.push('/login')
}

export const findIp = (string: string) => {

    let result = '';
    let match: any;

    if (match = string.match(new RegExp("\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b", 'gi'))) {
        result = match[0];
    }

    return result;
}
export const getOpusFormatNumber = (sdp: any) => {

    const lines = sdp.split('\r\n');
    let opusFormatNumber = -1;

    for (let i = 0; i < lines.length - 1; i++) {

        lines[i] = lines[i].toLowerCase();

        if (lines[i].indexOf('a=rtpmap') > -1 && lines[i].indexOf('opus') > -1) {
            // parsing "a=rtpmap:102 OPUS/48000/2" line
            opusFormatNumber = lines[i].split(' ')[0].split(':')[1];
            break;
        }
    }

    return opusFormatNumber;
}

export const checkOpusIsStereo = (sdp: any, opusFormatNumber: any) => {

    const lines = sdp.split('\r\n');

    let stereo = false;

    for (let i = 0; i < lines.length - 1; i++) {

        lines[i] = lines[i].toLowerCase();

        // check stereo=1 from "a=fmtp:102 sprop-stereo=1;stereo=1;minptime=10;useinbandfec=1"
        if (lines[i].indexOf('a=fmtp:' + opusFormatNumber) > -1) {

            if (lines[i].indexOf('stereo=1') > -1) {
                stereo = true;
            }
            break;
        }
    }

    return stereo;
}

export const mungeSdpForceStereoOpus = (sdp: any, opusFormatNumber: any) => {

    const lines = sdp.split('\r\n');

    // find this line and modify. "a=fmtp:102 minptime=10;useinbandfec=1"
    for (let i = 0; i < lines.length - 1; i++) {

        // check stereo=1 from "a=fmtp:102 sprop-stereo=1;stereo=1;minptime=10;useinbandfec=1"
        if (lines[i].indexOf('a=fmtp:' + opusFormatNumber) > -1) {

            if (lines[i].indexOf('stereo=1') === -1) {

                lines[i] = lines[i] + ';stereo=1';
            }
            break;
        }
    }

    return lines.join('\r\n');
}


export const  copyCandidate = (basicCandidate: any, webSocketUrl: string)=> {
    let currentBrowser = analUserAgent()
    let cloneCandidate = cloneDeep(basicCandidate);

    let newDomain = generateDomainFromUrl(webSocketUrl);
    let ip = findIp(cloneCandidate.candidate);

    return new Promise(function (resolve, reject) {

        if (ip === '' || ip === newDomain) {

            resolve(null);
        }

        // firefox browser throws a candidate parsing exception when a domain name is set at the address property. So we resolve the dns using google dns resolve api.
        if (currentBrowser.browser === 'Firefox' && !findIp(newDomain)) {

            resolve(null);

        } else {

            cloneCandidate.candidate = cloneCandidate.candidate.replace(ip, newDomain);
            resolve(cloneCandidate);
        }

    });
}

export const generateDomainFromUrl = (url: string) => {
    let result = '';
    let match: any;
    if (match = url.match(/^(?:wss?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n\?\=]+)/im)) {
        result = match[1];
    }

    return result;
}

// 使用RSA密码加密方式
export const encrypt = (text: any) => {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(
      `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt4VKlnBJ8ZqtL/975xzG
      0WrUlHjcJJwWifVscuJH6Gv652uVqb8B0c5cvB/sMGPhb6BObdFsiPwfwO3ahDem
      3pglH4Ugp/+auy8Hia8bXum4qXlVWvyXuXTZBXtqV8d5/scw4qXRXn5/PGX5nKHK
      3sDhs3rkE0FWE30C5jZ3EW+b58RRau5gogHyjSXEQybLkohCP0YkMj5wM4QZgSgU
      s1ch219wfl2X3BdMkU9whH4W28by3xJrUAcPcpHOBTF7TRGCmTmzLD9wz8QFnlU7
      7GYvduCA3Hp5bxzdsbmKeCWu5MFQQQ6cTRNRzGjKv5+FzLmv3efQRcO0yXIKRd6K
      kwIDAQAB`,
    );
    const encrypted = encrypt.encrypt(text);
    return encrypted;
  };

  export const  stringToBase64 = (input: string):string=>  {
    return btoa(input); // 将字符串转换为 Base64
}
